#include "sequence_list.h"

int dilatation = 2;  // 扩容系数
int initia_size = 8; // 初始大小

// 顺序表创建
arr_list *sequence_create()
{
    arr_list *list = (arr_list *)malloc(sizeof(arr_list));
    list->data = (void **)malloc(sizeof(void *) * initia_size);
    list->capacity = initia_size;
    list->size = 0;
    return list;
}

// 顺序表扩容,两倍
void sequence_dilatation(arr_list *list)
{
    if (list->size >= list->capacity)
    {
        void **pf = list->data;
        list->capacity *= dilatation;
        list->data = (void **)malloc(sizeof(void *) * initia_size);
        // 转移数据
        for (int i = 0; i <= list->size; i++)
        {
            list->data[i] = pf[i];
        }
        free(pf);
        pf = NULL;
    }
}

// 顺序表插入,尾插
arr_list *sequence_insert(arr_list *list, void *data)
{
    sequence_dilatation(list);
    list->data[list->size++] = data;
    return list;
}

// 删除指定位置的元素
int sequence_del_pos(arr_list *list, int position)
{
    if (position < 0)
    {
        return -1;
    }
    free(list->data[position]);
    list->data[position] = NULL;
    for (int i = position; i < list->size - 1; i++)
    {
        list->data[i] = list->data[i + 1];
    }
    list->size--;
    return 0;
}

// 清空顺序表
int sequence_clear(arr_list *list)
{
    if (list->data != NULL)
    {
        free(list->data);
        list->data == NULL;
    }
    list->data = (void **)malloc(sizeof(void *) * initia_size);
    list->capacity = initia_size;
    list->size = 0;
}

// 输出顺序表
void sequence_print_client(arr_list *l)
{
    printf("=============client data=============\n");
    for (int i = 0; i < l->size; i++)
    {
        printf("fd=%d,name=%s\n", ((client_data *)l->data[i])->fd, ((client_data *)l->data[i])->name);
    }
    printf("=============client data=============\n");
}